<?php if(!defined('BASEPATH')) exit('No direct script allowed access');
class Message_model extends CI_Model
{
	public function __construct(){
		parent::__construct();
		$this->load->library("session");
		$this->load->helper('common_function');
	}
	
	public function getOnlineFriend($uid){
		$sql1 = "select tb.*,`M`.`thread_id` from(SELECT `B`.`requester_id` AS reciver,
					   `U`.*
				FROM `tbl_network` AS B
				INNER JOIN `tbl_user_registration` AS U ON `U`.`user_id` = `B`.`requester_id`
				INNER JOIN `tbl_users_online` as ol ON ol.userid = `B`.`requester_id`
				WHERE `B`.`accepter_id` = '$uid') as tb
				INNER JOIN `tbl_message_thread` AS M ON (`M`.`sender_id` = `tb`.`reciver`
						AND M.receiver_id = '$uid')
						OR (M.sender_id = '$uid'
							AND M.receiver_id = tb.reciver)
				";
		$query = $this->db->query($sql1);//
		$reciver = $query->result();
		$sql2 = "select tb.*,`M`.`thread_id` from (SELECT `B`.`accepter_id` AS reciver,
					   `U`.*
				FROM `tbl_network` AS B
				INNER JOIN `tbl_user_registration` AS U ON `U`.`user_id` = `B`.`accepter_id`
				INNER JOIN `tbl_users_online` as ol ON ol.userid = `B`.`accepter_id`
				WHERE `B`.`requester_id` = '$uid') as tb
				INNER JOIN `tbl_message_thread` AS M ON (`M`.`sender_id` = `tb`.`reciver`
						AND M.receiver_id = '$uid')
						OR (M.sender_id = '$uid'
							AND M.receiver_id = tb.reciver)";
		$query2 = $this->db->query($sql2);
		//print_R($query2->result());die;
		$reciver = array_merge($reciver,$query2->result());
		 return $reciver;
	}
	
	public function show_thread_messages($thrdid,$usersid){
			//return "select * from (select * from tbl_message where `thread_id` = '$thrdid' order by created_date desc limit 10) as tb left join tbl_user_registration as U ON tb.sender_id = U.user_id order by tb.created_date asc" ;die;
			$threadmsg = $this->db->query("select *,UNIX_TIMESTAMP(tb.created_date) as msgtime from (select * from tbl_message where `thread_id` = '$thrdid' and delete_status<>'1' and delete_status<>'$usersid'  order by created_date desc limit 10) as tb left join tbl_user_registration as U ON tb.sender_id = U.user_id order by tb.created_date asc");
			if($threadmsg->num_rows()>0){
			return $threadmsg->result_array();
			}else{return 0;}
	}
	public function create_thread($uid,$id){
		
			//thread check if already created or not
			$thraedQuery = $this->db->query("select * from tbl_message_thread where (`sender_id`='$uid' and `receiver_id`='$id') or (`sender_id`='$id' and `receiver_id`='$uid')");
			if($thraedQuery->num_rows() < 1){
				$threadFields = array(
									'thread_id'=>unique(),
									'sender_id'=>$uid,
									'receiver_id'=>$id,
									'created_time'=> date('Y-m-d H:i:s')
									);
				$threadResponse = $this->db->insert('tbl_message_thread', $threadFields);
			}else{ return true; }
			
	}
}

?>